<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Http\Api\V1\Controller;

use Swoft\Http\Message\Response;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\Middleware;
use \Firebase\JWT\JWT;
use Swlib\Saber;
use Swlib\SaberGM;
use Swoft\Co;
use Swoft\Db\DB;
use Throwable;
use function context;
use EasySwoole\VerifyCode\Conf;
use App\Model\Entity\Article;
use Swoft\Validator\Annotation\Mapping\Validate;
use Swoft\Http\Message\Request;
use App\Exception\ApiException;

/**
 * Class UserController
 * @Controller("/api/v1/")
 * @Middleware(App\Http\Api\V1\Middleware\AuthMiddleware::class)
 */
class UserController
{
    /**
     * @RequestMapping("index")
     * @throws Throwable
     */
    public function index(): Response
    {
        $request = context()->getRequest();
        $uid = $request->query('uid',0);

        SaberGM::get('http://www.baidu.com');

        sgo(function(){
            $id = Co::id();
            vdump( $id );
        });

        $response = context()->getResponse();
        return $response->withStatus(200)->withData(['uid'=>$uid]);
    }

    /**
     * 抛出异常
     * @RequestMapping("err")
     * @throws Throwable
     */
    public function err(): String
    {
        throw new ApiException("这是一个错误",-2);
    }

    /**
     * jwt
     * @RequestMapping("jwt")
     * @throws Throwable
     */
    public function jwt(): Response
    {
        $key   = 'swoft';
        $time  = time();
        $token = [
            'iat'  => $time, //签发时间
            'nbf'  => $time, //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp'  => $time + 30, //过期时间
            'data' => [ //自定义信息，不要定义敏感信息
                'userid'   => 1,
                'username' => '张三',
            ],
        ];

        $jwt = JWT::encode($token, $key);
        $decoded = JWT::decode($jwt, $key, array('HS256'));
        $decoded_array = (array) $decoded;

        $json = ['code'=>200,'msg'=>'ok','data'=>['jwt_decode'=>$decoded_array,'jwt_encode'=>$jwt]];
        return context()->getResponse()->withStatus(200)->withData($json);
    }

    /**
     * db操作
     * @RequestMapping("db")
     * @throws Throwable
     */
    public function db(): Response
    {
        $user = DB::table('user')->where('username', 'Swoft')->first();
        if (!$user) {
            $id = DB::table('user')->insertGetId([
                'username' => 'Swoft',
                'password'  => 123456,
                'create_time'  => time()
            ]);
            $user['id'] = $id;
        }
        return context()->getResponse()->withStatus(200)->withData($user);
    }

    /**
     * 模型操作
     * @RequestMapping("model")
     * @throws Throwable
     */
    public function model(): Response
    {
        $article = Article::new();
        $article->setTitle('标题'.time());
        $article->setContent('内容'.time());
        $article->setCreateTime(time());
        $article->save();
        $id = $article->getId();
        return context()->getResponse()->withStatus(200)->withData(['id'=>$id]);
    }

    /**
     * 验证器
     * @RequestMapping("validator")
     * @Validate(validator="ArticleValidator",fields={"content"})
     * @Validate(validator="userValidator",fields={"title"})
     * @param Request $request
     * @return array
     */
    public function validator(Request $request)
    {
        return $request->getParsedBody();
    }

    /**
     * 生成验证码
     * @RequestMapping("vcode")
     * @throws Throwable
     */
    public function vcode(): Response
    {
        $config = new Conf();
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);
        $response = context()->getResponse();
        return $response
            ->withHeader('Content-Type','image/png')
            ->withContent($code->DrawCode()->getImageByte());
    }

    /**
     * 获取验证码信息
     * @RequestMapping("getVcode")
     * @throws Throwable
     */
    public function getVcode(): Response
    {
        $config = new Conf();
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);
        $response = context()->getResponse();
        return $response->withContent($code->DrawCode()->getImageBase64());
    }


}
